from PyQt6.QtWidgets import (QWidget, QVBoxLayout, QHBoxLayout, 
                           QLabel, QComboBox, QPushButton, QFrame,
                           QLineEdit, QCheckBox, QStackedWidget, QFileDialog, QMessageBox)
from PyQt6.QtCore import pyqtSignal, Qt
from PyQt6.QtGui import QKeySequence
from .base_page import BasePage
import json
import os
try:
    import openai
except ImportError:
    # 如果无法导入 openai，创建一个模拟对象
    class OpenAIMock:
        def __init__(self, *args, **kwargs):
            pass
            
        def chat(self, *args, **kwargs):
            return None
            
    openai = OpenAIMock()

# 添加一个自定义的 QLineEdit 类来禁用撤销功能
class SecureLineEdit(QLineEdit):
    def __init__(self, parent=None):
        super().__init__(parent)
    
    def keyPressEvent(self, event):
        # 如果是撤销快捷键，则忽略
        if event.matches(QKeySequence.StandardKey.Undo):
            event.ignore()
            return
        super().keyPressEvent(event)

class SettingCard(QFrame):
    def __init__(self, title, parent=None):
        super().__init__(parent)
        self.setObjectName("settingCard")
        self.setStyleSheet("""
            QFrame#settingCard {
                background-color: transparent;
                border-radius: 8px;
                padding: 15px;
            }
        """)
        
        layout = QVBoxLayout(self)
        layout.setSpacing(15)
        
        # 标题
        title_label = QLabel(title)
        title_label.setStyleSheet("""
            QLabel {
                font-size: 18px;
                font-weight: bold;
                color: #FFFFFF;
                background: transparent;
            }
        """)
        layout.addWidget(title_label)

class APISettingWidget(QWidget):
    def __init__(self, parent=None):
        super().__init__(parent)
        layout = QVBoxLayout(self)
        layout.setSpacing(10)
        
        # API Key 输入 - 使用新的 SecureLineEdit
        key_layout = QHBoxLayout()
        key_label = QLabel("API Key:")
        self.key_input = SecureLineEdit()  # 使用安全输入框
        self.key_input.setEchoMode(QLineEdit.EchoMode.Password)
        self.key_input.setPlaceholderText("请输入 API Key")
        self.key_input.textChanged.connect(self.on_setting_changed)
        
        key_layout.addWidget(key_label)
        key_layout.addWidget(self.key_input)
        layout.addLayout(key_layout)
        
        # Base URL 输入
        url_layout = QHBoxLayout()
        url_label = QLabel("Base URL:")
        self.url_input = QLineEdit()
        self.url_input.setPlaceholderText("请输入 API 基础地址")
        self.url_input.textChanged.connect(self.on_setting_changed)
        url_layout.addWidget(url_label)
        url_layout.addWidget(self.url_input)
        layout.addLayout(url_layout)
        
        # 模型选择
        model_layout = QHBoxLayout()
        model_label = QLabel("模型选择:")
        self.model_combo = QComboBox()
        self.model_combo.setMinimumWidth(300)  # 增加最小宽度
        self.model_combo.setMaximumWidth(400)  # 设置最大宽度
        self.model_combo.setSizeAdjustPolicy(QComboBox.SizeAdjustPolicy.AdjustToContents)  # 自动调整大小
        self.model_combo.setStyleSheet("""
            QComboBox {
                padding: 5px 10px;
                min-height: 25px;
            }
            QComboBox::drop-down {
                border: none;
                width: 30px;
                padding-right: 5px;
            }
            QComboBox::item {
                padding: 8px 10px;
                min-height: 25px;
            }
            QComboBox QAbstractItemView {
                min-width: 300px;  /* 下拉列表最小宽度 */
            }
        """)
        self.model_combo.addItems([
            "gpt-4-turbo-preview",
            "gpt-4",
            "gpt-4-32k",
            "gpt-4-0125-preview",
            "gpt-4o-mini",
            "gpt-3.5-turbo",
            "gpt-3.5-turbo-16k",
            "自定义"
        ])
        self.model_combo.currentTextChanged.connect(self.on_model_changed)
        self.model_combo.currentTextChanged.connect(self.on_setting_changed)
        model_layout.addWidget(model_label)
        model_layout.addWidget(self.model_combo, 1)  # 添加拉伸因子
        layout.addLayout(model_layout)
        
        # 自定义模型输入框
        self.custom_model_layout = QHBoxLayout()
        custom_model_label = QLabel("自定义模型:")
        self.custom_model_input = QLineEdit()
        self.custom_model_input.setPlaceholderText("请输入模型名称")
        self.custom_model_input.textChanged.connect(self.on_setting_changed)
        self.custom_model_input.hide()
        self.custom_model_layout.addWidget(custom_model_label)
        self.custom_model_layout.addWidget(self.custom_model_input)
        layout.addLayout(self.custom_model_layout)
        custom_model_label.hide()
        
        # 创建按钮容器
        button_layout = QHBoxLayout()
        button_layout.setSpacing(10)
        button_layout.addStretch()  # 添加弹性空间，使按钮靠右对齐
        
        # 添加测试按钮
        test_btn = QPushButton("测试连接")
        test_btn.setFixedSize(100, 32)  # 设置固定大小
        test_btn.clicked.connect(self.test_connection)
        test_btn.setStyleSheet("""
            QPushButton {
                background-color: #0C61F2;
                border: none;
                border-radius: 4px;
                color: white;
                font-weight: bold;
                padding: 0 15px;
            }
            QPushButton:hover {
                background-color: #1E74F4;
            }
            QPushButton:pressed {
                background-color: #0A4BC2;
            }
            QPushButton:disabled {
                background-color: rgba(12, 97, 242, 0.5);
            }
        """)
        button_layout.addWidget(test_btn)
        
        # 添加保存按钮
        save_btn = QPushButton("保存设置")
        save_btn.setFixedSize(100, 32)  # 设置固定大小
        save_btn.clicked.connect(self.save_settings)
        save_btn.setStyleSheet("""
            QPushButton {
                background-color: #0C61F2;
                border: none;
                border-radius: 4px;
                color: white;
                font-weight: bold;
                padding: 0 15px;
            }
            QPushButton:hover {
                background-color: #1E74F4;
            }
            QPushButton:pressed {
                background-color: #0A4BC2;
            }
            QPushButton:disabled {
                background-color: rgba(12, 97, 242, 0.5);
            }
        """)
        button_layout.addWidget(save_btn)
        
        # 将按钮布局添加到主布局
        layout.addSpacing(10)  # 添加一些垂直间距
        layout.addLayout(button_layout)
    
    def on_setting_changed(self):
        pass  # 不再自动保存
    
    def test_connection(self):
        try:
            # 检查必填项
            if not self.key_input.text():
                raise ValueError("请输入 API Key")
            
            if not self.url_input.text():
                raise ValueError("请填写 API 地址")
            
            # 配置 OpenAI 客户端
            client = openai.OpenAI(
                api_key=self.key_input.text(),
                base_url=self.url_input.text() if self.url_input.text() else None
            )
            
            # 发送测试消息
            response = client.chat.completions.create(
                model=self.get_model(),
                messages=[{"role": "user", "content": "你好"}],
                timeout=10
            )
            
            # 获取回复
            if not hasattr(response, 'choices'):
                raise ValueError("请检查 API 地址是否正确")
            
            reply = response.choices[0].message.content
            
            # 显示成功消息
            QMessageBox.information(
                self,
                "连接测试",
                f"连接成功！\nGPT回复: {reply}",
                QMessageBox.StandardButton.Ok
            )
            
        except ValueError as e:
            # 显示参数错误
            QMessageBox.warning(
                self,
                "参数错误",
                str(e),
                QMessageBox.StandardButton.Ok
            )
        except Exception as e:
            # 转换常见错误为中文提示
            error_msg = str(e).lower()  # 转换为小写以便匹配
            
            if "'str' object has no attribute 'choices'" in error_msg:
                error_msg = "请检查 API 地址是否正确"
            elif "invalid token" in error_msg or "invalid_token" in error_msg:
                error_msg = "API 密钥无效或已过期，请检查是否正确填写"
            elif "invalid api key" in error_msg or "incorrect api key" in error_msg:
                error_msg = "API 密钥格式错误，请检查是否正确复制"
            elif "invalid_request_error" in error_msg:
                error_msg = "请求参数无效，请检查 API 设置是否正确"
            elif "model" in error_msg and any(key in error_msg for key in ["not found", "does not exist", "invalid"]):
                error_msg = "选择的模型不可用，请更换其他模型"
            elif any(key in error_msg for key in ["timeout", "timed out"]):
                error_msg = "连接超时，请检查网络连接或代理设置"
            elif any(key in error_msg for key in ["no such host", "cannot connect", "connection refused", "failed to resolve"]):
                error_msg = "无法连接到 API 服务器，请检查：\n1. API 地址是否正确\n2. 网络连接是否正常\n3. 是否需要设置代理"
            elif "rate limit" in error_msg:
                error_msg = "请求频率超限，请稍后再试"
            elif any(key in error_msg for key in ["bad gateway", "502", "503", "504"]):
                error_msg = "服务器暂时无法响应，请稍后重试"
            elif "insufficient_quota" in error_msg:
                error_msg = "账户余额不足，请检查账户额度"
            elif "permission denied" in error_msg:
                error_msg = "没有访问权限，请检查 API 密钥权限设置"
            elif "not_found" in error_msg:
                error_msg = "请求的资源不存在，请检查 API 设置"
            elif "internal_server_error" in error_msg:
                error_msg = "服务器内部错误，请稍后重试"
            elif "bad_request" in error_msg:
                error_msg = "请求格式错误，请检查 API 设置"
            elif "unauthorized" in error_msg or "401" in error_msg:
                error_msg = "认证失败，请检查：\n1. API 密钥是否正确\n2. API 密钥是否已过期\n3. 账户是否有效"
            elif "forbidden" in error_msg or "403" in error_msg:
                error_msg = "访问被拒绝，请检查 API 密钥权限"
            elif "service unavailable" in error_msg:
                error_msg = "服务暂时不可用，请稍后重试"
            else:
                error_msg = f"连接失败：{error_msg}"
            
            # 显示错误消息
            QMessageBox.critical(
                self,
                "连接测试",
                error_msg,
                QMessageBox.StandardButton.Ok
            )
    
    def on_model_changed(self, model):
        # 当选择"自定义"时显示自定义模型输入框
        is_custom = model == "自定义"
        self.custom_model_input.setVisible(is_custom)
        self.custom_model_layout.itemAt(0).widget().setVisible(is_custom)  # 显示/隐藏标签
    
    def get_model(self):
        # 获取当前选择的模型
        model = self.model_combo.currentText()
        if model == "自定义":
            return self.custom_model_input.text()
        return model
    
    def save_settings(self):
        # 修改获取 SettingsPage 实例的方式
        settings_page = None
        parent = self.parent()
        
        # 向上查找 SettingsPage 实例
        while parent is not None:
            if isinstance(parent, SettingsPage):
                settings_page = parent
                break
            parent = parent.parent()
        
        if settings_page:
            settings_page.save_api_settings()
            # 显示保存成功提示
            QMessageBox.information(
                self,
                "保存成功",
                "API 设置已保存",
                QMessageBox.StandardButton.Ok
            )
        else:
            QMessageBox.warning(
                self,
                "保存失败",
                "无法找到设置页面",
                QMessageBox.StandardButton.Ok
            )

class PathSettingWidget(QWidget):
    def __init__(self, title, default_path, parent=None):
        super().__init__(parent)
        layout = QHBoxLayout(self)
        layout.setContentsMargins(0, 0, 0, 0)
        
        # 路径输入框
        self.path_input = QLineEdit(default_path)
        self.path_input.setReadOnly(True)
        self.path_input.setPlaceholderText("请选择保存路径")
        self.path_input.setStyleSheet("""
            QLineEdit {
                background: transparent;
                border: 1px solid rgba(255, 255, 255, 0.1);
                border-radius: 4px;
                padding: 5px 10px;
                color: #FFFFFF;
            }
            QLineEdit:focus {
                border-color: #0C61F2;
            }
        """)
        
        # 选择按钮
        select_btn = QPushButton("选择")
        select_btn.setFixedWidth(80)
        select_btn.clicked.connect(self.select_path)
        
        # 标题标签
        title_label = QLabel(title)
        title_label.setStyleSheet("background: transparent;")
        
        layout.addWidget(title_label)
        layout.addWidget(self.path_input)
        layout.addWidget(select_btn)
    
    def select_path(self):
        path = QFileDialog.getExistingDirectory(
            self,
            "选择保存路径",
            self.path_input.text(),
            QFileDialog.Option.ShowDirsOnly
        )
        if path:
            self.path_input.setText(path)
    
    def get_path(self):
        return self.path_input.text()

class SettingsPage(BasePage):
    apiSettingsChanged = pyqtSignal(dict)  # API设置变更信号
    pathsChanged = pyqtSignal(dict)  # 路径变更信号
    
    def __init__(self):
        super().__init__()  # 这会创建 self.main_layout
        self.settings_file = 'settings.json'
        self.loading_settings = False  # 添加一个标志来标识是否正在加载设置
        self.init_ui()
        self.load_settings()
        
    def init_ui(self):
        # 页面标题
        self.set_title("设置")
        
        # API设置卡片
        api_card = SettingCard("API 设置")
        api_layout = QVBoxLayout()
        
        # API提供商选择
        provider_group = self.create_group("API 提供商")
        provider_layout = QVBoxLayout()
        
        # 提供商选择
        self.provider_combo = QComboBox()
        self.provider_combo.addItems([
            "OpenAI 官方",
            "Azure OpenAI",
            "智谱 AI",
            "百度文心",
            "讯飞星火",
            "通义千问",
            "自定义"
        ])
        self.provider_combo.currentTextChanged.connect(self.on_provider_changed)
        provider_layout.addWidget(self.provider_combo)
        
        # API设置堆叠窗口
        self.api_stack = QStackedWidget()
        
        # OpenAI官方设置
        openai_widget = APISettingWidget()
        openai_widget.url_input.setText("https://api.openai.com/v1")
        self.api_stack.addWidget(openai_widget)
        
        # Azure设置
        azure_widget = APISettingWidget()
        azure_widget.url_input.setPlaceholderText("请输入 Azure OpenAI 终结点")
        self.api_stack.addWidget(azure_widget)
        
        # 智谱AI设置
        zhipu_widget = APISettingWidget()
        zhipu_widget.url_input.setText("https://open.bigmodel.cn/api/paas/v3")
        self.api_stack.addWidget(zhipu_widget)
        
        # 百度文心设置
        baidu_widget = APISettingWidget()
        baidu_widget.key_input.setPlaceholderText("请输入 API Key")
        key2_layout = QHBoxLayout()
        key2_label = QLabel("Secret Key:")
        key2_input = QLineEdit()
        key2_input.setEchoMode(QLineEdit.EchoMode.Password)
        key2_input.setPlaceholderText("请输入 Secret Key")
        key2_layout.addWidget(key2_label)
        key2_layout.addWidget(key2_input)
        baidu_widget.layout().addLayout(key2_layout)
        self.api_stack.addWidget(baidu_widget)
        
        # 讯飞星火设置
        xunfei_widget = APISettingWidget()
        xunfei_widget.url_input.setText("https://spark-api.xf-yun.com/v2.1")
        self.api_stack.addWidget(xunfei_widget)
        
        # 通义千问设置
        tongyi_widget = APISettingWidget()
        tongyi_widget.url_input.setText("https://dashscope.aliyuncs.com/api/v1")
        self.api_stack.addWidget(tongyi_widget)
        
        # 自定义设置
        custom_widget = APISettingWidget()
        custom_widget.url_input.setPlaceholderText("请输入完整的API地址")
        self.api_stack.addWidget(custom_widget)
        
        provider_layout.addWidget(self.api_stack)
        provider_group.layout().addLayout(provider_layout)
        
        # 代理设置
        proxy_group = self.create_group("代理设置")
        proxy_layout = QVBoxLayout()
        
        # 启用代理选项
        self.enable_proxy = QCheckBox("启用代理")
        self.enable_proxy.setStyleSheet("""
            QCheckBox {
                background: transparent;
                color: #FFFFFF;
            }
            QCheckBox::indicator {
                width: 18px;
                height: 18px;
                background: transparent;
                border: 2px solid rgba(255, 255, 255, 0.3);
                border-radius: 4px;
            }
            QCheckBox::indicator:checked {
                background: #0C61F2;
                border-color: #0C61F2;
            }
        """)
        
        # 代理地址输入
        proxy_url_layout = QHBoxLayout()
        proxy_label = QLabel("代理地址:")
        proxy_label.setStyleSheet("background: transparent;")
        self.proxy_url = QLineEdit()
        self.proxy_url.setEnabled(False)
        self.proxy_url.setPlaceholderText("例如: http://127.0.0.1:7890")
        self.proxy_url.setStyleSheet("""
            QLineEdit {
                background: transparent;
                border: 1px solid rgba(255, 255, 255, 0.1);
                border-radius: 4px;
                padding: 5px 10px;
                color: #FFFFFF;
            }
            QLineEdit:focus {
                border-color: #0C61F2;
            }
            QLineEdit:disabled {
                color: rgba(255, 255, 255, 0.3);
                border-color: rgba(255, 255, 255, 0.05);
            }
        """)
        
        proxy_url_layout.addWidget(proxy_label)
        proxy_url_layout.addWidget(self.proxy_url)
        
        proxy_layout.addWidget(self.enable_proxy)
        proxy_layout.addLayout(proxy_url_layout)
        proxy_group.layout().addLayout(proxy_layout)
        
        # 添加到API设置卡片
        api_layout.addWidget(provider_group)
        api_layout.addWidget(proxy_group)
        api_card.layout().addLayout(api_layout)
        
        # 添加到主布局
        self.main_layout.addWidget(api_card)
        
        # 路径设置卡片
        paths_card = SettingCard("路径设置")
        paths_layout = QVBoxLayout()
        
        # 创建路径设置组
        paths_group = self.create_group("保存路径")
        paths_group_layout = QVBoxLayout()
        
        # 获取默认下载路径
        default_download_path = os.path.join(os.path.expanduser("~"), "Downloads", "喵神AI")
        default_writing_path = os.path.join(os.path.expanduser("~"), "Documents", "喵神AI")
        
        # 小说下载路径
        self.novel_path = PathSettingWidget(
            "小说下载路径：",
            default_download_path
        )
        paths_group_layout.addWidget(self.novel_path)
        
        # 文本创作路径
        self.writing_path = PathSettingWidget(
            "文本创作路径：",
            default_writing_path
        )
        paths_group_layout.addWidget(self.writing_path)
        
        # 保存按钮
        save_btn = QPushButton("保存设置")
        save_btn.setFixedWidth(120)
        save_btn.clicked.connect(self.save_paths)
        save_btn.setStyleSheet("""
            QPushButton {
                background-color: #0C61F2;
                border-radius: 4px;
                color: white;
                font-weight: bold;
                padding: 8px;
            }
            QPushButton:hover {
                background-color: #1E74F4;
            }
            QPushButton:pressed {
                background-color: #0A4BC2;
            }
        """)
        
        paths_group_layout.addWidget(save_btn, alignment=Qt.AlignmentFlag.AlignRight)
        paths_group.layout().addLayout(paths_group_layout)
        
        paths_layout.addWidget(paths_group)
        paths_card.layout().addLayout(paths_layout)
        
        # 添加到主布局
        self.main_layout.addWidget(paths_card)
        
        self.main_layout.addStretch()
    
    def load_settings(self):
        """加载所有设置"""
        self.loading_settings = True  # 开始加载
        try:
            if os.path.exists(self.settings_file):
                try:
                    with open(self.settings_file, 'r', encoding='utf-8') as f:
                        settings = json.load(f)
                        
                        # 加载API设置
                        api_settings = settings.get('api_settings', {})
                        if api_settings:
                            # 设置提供商
                            provider = api_settings.get('provider', 'OpenAI 官方')
                            self.provider_combo.setCurrentText(provider)
                            
                            # 根据提供商选择对应的设置页面
                            index = self.provider_combo.currentIndex()
                            self.api_stack.setCurrentIndex(index)
                            
                            # 设置API信息
                            current_widget = self.api_stack.currentWidget()
                            current_widget.key_input.setText(api_settings.get('api_key', ''))
                            current_widget.url_input.setText(api_settings.get('base_url', ''))
                            
                            # 设置代理
                            enable_proxy = api_settings.get('enable_proxy', False)
                            self.enable_proxy.setChecked(enable_proxy)
                            self.proxy_url.setEnabled(enable_proxy)
                            self.proxy_url.setText(api_settings.get('proxy_url', ''))
                            
                            # 特殊处理百度文心的额外密钥
                            if provider == "百度文心":
                                self.api_stack.widget(3).layout().itemAt(2).itemAt(1).widget().setText(
                                    api_settings.get('secret_key', '')
                                )
                            
                            # 加载模型设置
                            model = api_settings.get('model', 'gpt-3.5-turbo')
                            if model in [
                                "gpt-4-turbo-preview",
                                "gpt-4",
                                "gpt-4-32k",
                                "gpt-4-0125-preview",
                                "gpt-4o-mini",
                                "gpt-3.5-turbo",
                                "gpt-3.5-turbo-16k"
                            ]:
                                current_widget.model_combo.setCurrentText(model)
                            else:
                                current_widget.model_combo.setCurrentText("自定义")
                                current_widget.custom_model_input.setText(model)
                                current_widget.custom_model_input.setVisible(True)
                                current_widget.custom_model_layout.itemAt(0).widget().setVisible(True)
                            
                            # 加载完成后发送设置变更信号
                            self.apiSettingsChanged.emit(api_settings)
                        
                        # 加载路径设置
                        paths = settings.get('paths', {})
                        if paths:
                            if 'novel_download' in paths:
                                self.novel_path.path_input.setText(paths['novel_download'])
                            if 'writing' in paths:
                                self.writing_path.path_input.setText(paths['writing'])
                            self.pathsChanged.emit(paths)
                except Exception as e:
                    print(f"加载设置时出错: {str(e)}")
            else:
                # 如果设置文件不存在，创建默认设置
                self.save_api_settings()
                self.save_paths()
        finally:
            self.loading_settings = False  # 确保加载完成后重置标志
    
    def create_group(self, title):
        """创建一个带标题的设置组"""
        group = QFrame()
        group.setObjectName("settingsGroup")
        
        group_layout = QVBoxLayout(group)
        group_layout.setContentsMargins(15, 15, 15, 15)
        group_layout.setSpacing(10)
        
        # 添加标题
        title_label = QLabel(title)
        title_label.setObjectName("groupTitle")
        group_layout.addWidget(title_label)
        
        # 添加分割线
        line = QFrame()
        line.setFrameShape(QFrame.Shape.HLine)
        line.setObjectName("separator")
        group_layout.addWidget(line)
        
        return group
    
    def on_provider_changed(self, provider):
        if not self.loading_settings:  # 只有在非加载状态时才保存
            index = self.provider_combo.currentIndex()
            self.api_stack.setCurrentIndex(index)
            self.save_api_settings()
    
    def on_proxy_changed(self, state):
        if not self.loading_settings:  # 只有在非加载状态时才保存
            self.proxy_url.setEnabled(state == Qt.CheckState.Checked.value)
            self.save_api_settings()
    
    def save_api_settings(self):
        """保存 API 设置"""
        try:
            # 读取现有设置（如果文件存在）
            if os.path.exists(self.settings_file):
                with open(self.settings_file, 'r', encoding='utf-8') as f:
                    settings = json.load(f)
            else:
                settings = {}
            
            # 获取当前 API 设置
            current_widget = self.api_stack.currentWidget()
            api_settings = {
                'provider': self.provider_combo.currentText(),
                'api_key': current_widget.key_input.text(),
                'base_url': current_widget.url_input.text(),
                'model': current_widget.get_model(),
                'enable_proxy': self.enable_proxy.isChecked(),
                'proxy_url': self.proxy_url.text() if self.enable_proxy.isChecked() else ''
            }
            
            # 特殊处理百度文心的额外密钥
            if self.provider_combo.currentText() == "百度文心":
                api_settings['secret_key'] = self.api_stack.widget(3).layout().itemAt(2).itemAt(1).widget().text()
            
            # 更新设置
            settings['api_settings'] = api_settings
            
            # 保存到文件
            with open(self.settings_file, 'w', encoding='utf-8') as f:
                json.dump(settings, f, ensure_ascii=False, indent=2)
            
            # 发送信号
            self.apiSettingsChanged.emit(api_settings)
            
        except Exception as e:
            print(f"保存API设置时出错: {str(e)}")
            QMessageBox.warning(
                self,
                "保存失败",
                f"保存设置时出错: {str(e)}",
                QMessageBox.StandardButton.Ok
            )
    
    def save_paths(self):
        try:
            # 读取现有设置（如果文件存在）
            if os.path.exists(self.settings_file):
                with open(self.settings_file, 'r', encoding='utf-8') as f:
                    settings = json.load(f)
            else:
                settings = {}
            
            # 准备路径设置
            paths = {
                'novel_download': self.novel_path.get_path(),
                'writing': self.writing_path.get_path()
            }
            
            # 确保目录存在
            for path in paths.values():
                try:
                    os.makedirs(path, exist_ok=True)
                except Exception as e:
                    QMessageBox.warning(
                        self,
                        "创建目录失败",
                        f"创建目录时出错: {str(e)}",
                        QMessageBox.StandardButton.Ok
                    )
                    return
            
            # 更新设置中的路径部分，保留其他设置
            settings['paths'] = paths
            
            # 保存所有设置到文件
            with open(self.settings_file, 'w', encoding='utf-8') as f:
                json.dump(settings, f, ensure_ascii=False, indent=2)
            
            # 发送信号
            self.pathsChanged.emit(paths)
            
            # 显示保存成功提示
            QMessageBox.information(
                self,
                "保存成功",
                "路径设置已保存",
                QMessageBox.StandardButton.Ok
            )
            
        except Exception as e:
            QMessageBox.warning(
                self,
                "保存失败",
                f"保存路径设置时出错: {str(e)}",
                QMessageBox.StandardButton.Ok
            )
    
    def apply_theme(self, theme):
        is_dark = theme == "深色主题"
        
        if is_dark:
            self.setStyleSheet("""
                /* 卡片样式 */
                QFrame#settingCard {
                    background-color: transparent;
                }
                
                /* 设置组样式 */
                QFrame#settingsGroup {
                    background-color: transparent;  /* 修改为透明 */
                    border-radius: 8px;
                }
                
                /* 标题样式 */
                QLabel#groupTitle {
                    font-size: 14px;
                    font-weight: bold;
                    color: #FFFFFF;
                    background: transparent;
                }
                
                /* 分割线样式 */
                QFrame#separator {
                    background-color: rgba(255, 255, 255, 0.1);
                }
                
                /* 代理设置样式 */
                QCheckBox {
                    background: transparent;
                    color: #FFFFFF;
                }
                QCheckBox::indicator {
                    width: 18px;
                    height: 18px;
                    background: transparent;
                    border: 2px solid rgba(255, 255, 255, 0.3);
                    border-radius: 4px;
                }
                QCheckBox::indicator:checked {
                    background: #0C61F2;
                    border-color: #0C61F2;
                }
                
                QLabel {
                    background: transparent;
                    color: #FFFFFF;
                }
                
                QLineEdit {
                    background: transparent;
                    border: 1px solid rgba(255, 255, 255, 0.1);
                    border-radius: 4px;
                    padding: 5px 10px;
                    color: #FFFFFF;
                }
                QLineEdit:focus {
                    border-color: #0C61F2;
                }
                QLineEdit:disabled {
                    color: rgba(255, 255, 255, 0.3);
                    border-color: rgba(255, 255, 255, 0.05);
                }
                
                /* 其他样式保持不变... */
            """)
        else:
            self.setStyleSheet("""
                /* 移除卡片背景色 */
                QFrame#settingCard {
                    background: transparent;
                }
                
                /* 设置组样式 */
                QFrame#settingsGroup {
                    background: transparent;
                    border-radius: 8px;
                    margin-top: 10px;
                }
                
                /* 标题样式 */
                QLabel#groupTitle {
                    font-size: 14px;
                    font-weight: bold;
                    color: #333333;
                }
                
                /* 分割线样式 */
                QFrame#separator {
                    background-color: #E0E0E0;
                }
                
                /* 输入框样式 */
                QLineEdit {
                    background-color: #FFFFFF;
                    border: 1px solid #E0E0E0;
                    border-radius: 4px;
                    padding: 5px 10px;
                    color: #333333;
                }
                QLineEdit:focus {
                    border-color: #0C61F2;
                }
                
                /* 下拉框样式 */
                QComboBox {
                    background-color: #FFFFFF;
                    border: 1px solid #E0E0E0;
                    border-radius: 4px;
                    padding: 5px 10px;
                    color: #333333;
                }
                QComboBox:hover {
                    border-color: #0C61F2;
                }
                
                /* 其他样式保持不变... */
            """) 